summaryrefslogtreecommitdiff
path: root/src/pages/blog/[...date].astro
blob: c88fc1a0ee9b4c4c4d7bab4a148d0e14f39de7e5 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
---
import type {
  GetStaticPaths,
  GetStaticPathsItem,
  InferGetStaticParamsType,
  InferGetStaticPropsType,
} from "astro";
import Base from "@layouts/Base.astro";
import PrevNext from "@layouts/PrevNext.astro";
import DateSelector from "@components/DateSelector.astro";
import SimplePostList from "@components/templates/SimplePostList.astro";
import { fromPosts, isEntry, sortLastCreated } from "@lib/collection/helpers";
import type { Entry } from "@lib/collection/schemas";
import { identity } from "@utils/anonymous";

export const getStaticPaths = (async (): Promise<
  {
    params: { date?: string };
    props: {
      posts: Entry[];
      next?: string;
      previous?: string;
      years: number[];
      months: number[];
      days?: number[];
    };
  }[]
> => {
  const posts = await fromPosts(isEntry, identity);

  const archive = {
    years: new Set<number>(),
    monthsByYear: new Map<string, Set<number>>(),
    daysByMonth: new Map<string, Set<number>>(),
    postsByDate: new Map<string, typeof posts>(),
    sortedDates: [] as string[],
  };

  const getYMD = (date: Date) => {
    const y = date.getFullYear();
    const m = date.getMonth() + 1;
    const d = date.getDate();
    return { y, m, d };
  };

  for (const post of posts) {
    const { y, m, d } = getYMD(post.data.dateCreated);

    archive.years.add(y);

    const months = archive.monthsByYear.get(y.toString());
    if (months === undefined) {
      archive.monthsByYear.set(y.toString(), new Set([m]));
    } else {
      months.add(m);
    }

    const ym = `${y}/${String(m).padStart(2, "0")}`;
    const days = archive.daysByMonth.get(ym);
    if (days === undefined) {
      archive.daysByMonth.set(ym, new Set([d]));
    } else {
      days.add(d);
    }

    const ymd = `${ym}/${String(d).padStart(2, "0")}`;
    const posts = archive.postsByDate.get(ymd);
    if (posts === undefined) {
      archive.postsByDate.set(ymd, [post]);
    } else {
      posts.push(post);
    }
  }

  archive.sortedDates = Array.from(archive.postsByDate.keys()).sort();

  const paths: {
    params: { date?: string };
    props: {
      posts: Entry[];
      next?: string;
      previous?: string;
      years: number[];
      months: number[];
      days?: number[];
    };
  }[] = [] satisfies GetStaticPathsItem[];

  const sortedYears = Array.from(archive.years).sort();

  const lastYear = Math.max(...sortedYears.map(Number));
  paths.push({
    params: { date: undefined },
    props: {
      posts: posts.filter((p) =>
        p.data.dateCreated.getFullYear() === lastYear
      ),
      next: undefined,
      previous: sortedYears?.[sortedYears.length - 2]?.toString(),
      years: sortedYears,
      months: Array.from(archive.monthsByYear.get(lastYear.toString()) ?? []),
    },
  });

  for (const y of sortedYears) {
    const yearPosts = posts.filter((p) =>
      p.data.dateCreated.getFullYear() === Number(y)
    );
    const idx = sortedYears.indexOf(y);
    paths.push({
      params: { date: y.toString() },
      props: {
        posts: yearPosts,
        next: sortedYears?.[idx + 1]?.toString(),
        previous: sortedYears?.[idx - 1]?.toString(),
        years: sortedYears,
        months: Array.from(archive.monthsByYear.get(y.toString()) ?? []),
      },
    });
  }

  const allMonths = Array.from(archive.monthsByYear.entries())
    .flatMap(([year, mset]) =>
      Array.from(mset).map((m) => `${year}/${String(m).padStart(2, "0")}`)
    )
    .sort();

  for (const [y, months] of archive.monthsByYear) {
    const sortedMonths = Array.from(months).sort();
    for (const m of sortedMonths) {
      const monthPosts = posts.filter((p) => {
        const d = p.data.dateCreated;
        return (
          d.getFullYear() === Number(y) &&
          d.getMonth() + 1 === m
        );
      });

      const ym = `${y}/${String(m).padStart(2, "0")}`;
      const idx = allMonths.indexOf(ym);

      paths.push({
        params: { date: ym },
        props: {
          posts: monthPosts,
          next: allMonths?.[idx + 1],
          previous: allMonths?.[idx - 1],
          years: sortedYears,
          months: Array.from(months).sort(),
          days: Array.from(archive.daysByMonth.get(ym) ?? []).sort(),
        },
      });
    }
  }

  for (let i = 0; i < archive.sortedDates.length; i++) {
    const ymd = archive.sortedDates[i];
    const [y, m] = ymd.split("/");
    paths.push({
      params: { date: ymd },
      props: {
        posts: archive.postsByDate.get(ymd) ?? [],
        next: archive.sortedDates?.[i + 1],
        previous: archive.sortedDates?.[i - 1],
        years: sortedYears,
        months: Array.from(archive.monthsByYear.get(y) ?? []).sort(),
        days: Array.from(archive.daysByMonth.get(`${y}/${m}`) ?? []).sort(),
      },
    });
  }

  return paths;
}) satisfies GetStaticPaths;

export type Params = InferGetStaticParamsType<typeof getStaticPaths>;
export type Props = InferGetStaticPropsType<typeof getStaticPaths>;

let { posts, previous, next, years, months, days } = Astro.props;
posts = posts.sort(sortLastCreated);

const dateParts = Astro.params.date?.split("/").map(Number);
const y = dateParts?.[0];
const m = dateParts?.[1] ?? 1;
const d = dateParts?.[2] ?? 3;
const date = (y !== undefined) ? new Date(Date.UTC(y, m - 1, d)) : undefined;

const format = date === undefined
  ? undefined
  : new Intl.DateTimeFormat("pt-PT", {
    year: y === undefined ? undefined : "numeric",
    month: dateParts?.[1] === undefined ? undefined : "long",
    day: dateParts?.[2] === undefined ? undefined : "numeric",
  }).format(date);
const title = "Publicações" +
  (format !== undefined ? ` &ndash; ${format}` : "");
const description = "Ultímas publicações" +
  (format !== undefined ? ` do dia ${format}` : "") + ".";
---

<Base {title} {description}>
  <main
    itemprop="mainContentOfPage"
    itemscope
    itemtype="https://schema.org/WebPageElement"
  >
    <section
      id="posts"
      itemprop="citation"
      itemscope
      itemtype="http://schema.org/Blog"
    >
      <h2 itemprop="name description" set:html={title} />
      <DateSelector {date} {years} {months} {days} />
      <PrevNext
        previous={previous === undefined ? undefined : `/blog/${previous}`}
        next={next === undefined ? undefined : `/blog/${next}`}
        label={format}
      >
        <SimplePostList
          {posts}
          dateOptions={{
            weekday: "long",
            year: "numeric",
            month: "long",
            day: "numeric",
            hour: "2-digit",
            minute: "2-digit",
            timeZoneName: "long",
          }}
        />
      </PrevNext>
      <DateSelector {date} {years} {months} {days} />
    </section>
  </main>
</Base>